package cn.wen.rpc.netty.handler;

import cn.wen.rpc.exception.WenRpcException;
import cn.wen.rpc.factory.SingletonFactory;
import cn.wen.rpc.message.WenRequest;
import cn.wen.rpc.server.WenServiceProvider;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

@Slf4j
public class WenRequestHandler {

    private WenServiceProvider wenServiceProvider;

    public WenRequestHandler(){
        wenServiceProvider = SingletonFactory.getInstance(WenServiceProvider.class);
    }

    public Object handler(WenRequest msRequest) {
        String interfaceName = msRequest.getInterfaceName();
        String version = msRequest.getVersion();
        Object service = wenServiceProvider.getService(interfaceName + version);
        if (service == null){
            throw new WenRpcException("没有找到可用的服务提供方");
        }
        try {
            Method method = service.getClass().getMethod(msRequest.getMethodName(), msRequest.getParamTypes());
            return method.invoke(service, msRequest.getParameters());
        } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            log.info("服务提供方 方法调用 出现问题:",e);
        }

        return null;
    }
}
